package org.vacoor.xqq.ui.dynamictree;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.xqq.ui.comp.tooltip.TooltipWindow;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;

/**
 * User: vacoor
 */
public class TreeNodeMouseEventListener extends TreeNodeMouseEventAdapter {
    private static final Logger logger = LoggerFactory.getLogger(TreeNodeMouseEventListener.class);
    private TooltipWindow tooltip = new TooltipWindow();

    public TreeNodeMouseEventListener() {
        init();
    }

    private void init() {
        tooltip.setSize(230, 160);
        tooltip.getContentPane().setBackground(new Color(200, 200, 200));
        tooltip.setVisible(false);
    }


    // ------------------------- Tooltip 控制
    @Override
    public void mouseMovedOnNode(MouseEvent e, int row, Point point) {
        JTree tree = (JTree) e.getSource();

        // 如果不是叶子, 直接返回
        if (!((DefaultMutableTreeNode) tree.getPathForRow(row).getLastPathComponent()).isLeaf()) {
            return;
        }

        Rectangle bounds = tree.getRowBounds(row);

        // 事件触发区域
        Rectangle trigerBounds = new Rectangle(10, 5, bounds.height - 10, bounds.height - 10);

        if (trigerBounds.contains(point)) {
            int containerX = tree.getLocationOnScreen().x;
            int width = tree.getWidth();

            Window win = SwingUtilities.getWindowAncestor(tree);
            if (win != null) {
                containerX = win.getLocationOnScreen().x;
                width = win.getWidth();
            }

            int x = containerX - tooltip.getWidth() - 10;
            if (x < -20) {
                x = containerX + width + 10;
            }

            int y = (int) (tree.getLocationOnScreen().getY() + bounds.getY() - 20);

            if (!this.tooltip.isVisible()) {
                this.tooltip.setLocation(x, y);
                this.tooltip.delayShow(1200);
            }
        } else {
            tooltip.cancelDelayShow();
            tooltip.setVisible(false);
        }
    }

    @Override
    public void mouseExitedOnNode(MouseEvent e, int row, Point point) {
        tooltip.cancelDelayShow();
        tooltip.setVisible(false);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        tooltip.cancelDelayShow();
        tooltip.setVisible(false);
    }

    // ------------------------------------

    @Override
    public void mouseClicked(MouseEvent e) {
        JTree tree = (JTree) e.getSource();
        TreePath path = tree.getPathForLocation(e.getX(), e.getY());
        if (null == path || !SwingUtilities.isLeftMouseButton(e) || e.getClickCount() < 2) {
            return;
        }

        Object node = tree.getLastSelectedPathComponent();
        if (!(node instanceof BuddyNode)) {
            return;
        }
        BuddyNode n = (BuddyNode) node;
    }
}
